package xyz.labmem.base.sys.aop

import cn.dev33.satoken.stp.StpUtil
import org.aspectj.lang.JoinPoint
import org.aspectj.lang.annotation.AfterReturning
import org.aspectj.lang.annotation.AfterThrowing
import org.aspectj.lang.annotation.Aspect
import org.aspectj.lang.annotation.Pointcut
import org.aspectj.lang.reflect.MethodSignature
import org.springframework.core.annotation.Order
import org.springframework.stereotype.Component
import xyz.labmem.base.core.annotion.BusinessLog
import xyz.labmem.base.core.consts.AopSortConstant
import xyz.labmem.base.core.consts.UNKNOWN
import xyz.labmem.base.core.tool.toJsonStr
import xyz.labmem.base.sys.base.BaseController
import xyz.labmem.base.sys.util.LogManager

/**
 *业务日志aop切面
 * @Author lty
 * @Date 2021/12/15 14:46
 */
@Aspect
@Component
@Order(AopSortConstant.BUSINESS_LOG_AOP)
class BusinessLogAop {

    /**
     * 日志切入点
     */
    @Pointcut("@annotation(xyz.labmem.base.core.annotion.BusinessLog)")
    private fun getLogPointCut() {}


    /**
     * 操作成功返回结果记录日志
     *
     */
    @AfterReturning(pointcut = "getLogPointCut()", returning = "result")
    fun doAfterReturning(joinPoint: JoinPoint, result: Any) {
        val methodSignature = joinPoint.signature as MethodSignature
        val method = methodSignature.method
        val businessLog: BusinessLog = method.getAnnotation(BusinessLog::class.java)
        var account: String = UNKNOWN
        if (StpUtil.isLogin()) {
            account = BaseController.getLoginUser().account!!
        }
        //异步记录日志
        LogManager.me().executeOperationLog(
            businessLog, account, joinPoint, result.toJsonStr()
        )
    }

    /**
     * 操作发生异常记录日志
     *
     */
    @AfterThrowing(pointcut = "getLogPointCut()", throwing = "exception")
    fun doAfterThrowing(joinPoint: JoinPoint, exception: Exception) {
        val methodSignature = joinPoint.signature as MethodSignature
        val method = methodSignature.method
        val businessLog: BusinessLog = method.getAnnotation(BusinessLog::class.java)
        var account: String = UNKNOWN
        if (StpUtil.isLogin()) {
            account = BaseController.getLoginUser().account!!
        }
        //异步记录日志
        LogManager.me().executeExceptionLog(
            businessLog, account, joinPoint, exception
        )
    }


}